<template>
  <!-- 客户端请求 -->
  <div class="card text-center ms-2 me-4 mt-2 mb-2">
    <div class="card-body">
      <h5 class="">用户状态</h5>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in TraceClients" :key="'user_' + index" scope="col">{{ user.name }}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>请求状态</td>
              <td class="text-white" v-for="(user, index) in TraceClients" :key="'user_status_' + index"
                :class="user.status ? 'bg-primary-heavy' : 'bg-secondary-light'">
                {{(user.status ? '请求追踪' : '未请求') }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<!-- 按钮 -->
  <div class="d-flex justify-content-center mt-2 mb-2" >
    <div class="card mx-auto text-center btn bg-primary-heavy" :class="buttonClass" @click="start_trace" style="width: 30%; aspect-ratio: 14/4;">
      <div class="card-body d-flex align-items-center justify-content-center" >
        <h5 class="m-0 text-white">开始追踪</h5>
      </div>
    </div>
  </div>
  <p>追踪时间: {{ responseTime }} 秒</p>
<!-- 追踪服务器状态 -->
  <div class="card text-center  ms-2 me-4 mt-2 mb-2">
    <div class="card-body ">
      <h5 class="">追踪服务器</h5>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in TraceResult" :key="'user_' + index" scope="col">{{ user.name }}</th>
            </tr>
          </thead>
          <tbody>
            <tr >
              <td>状态</td>
              <td class="text-white" v-for="(user, index) in TraceResult" :key="'user_status_' + index" :class="{ 'bg-primary-heavy': user.status, 'bg-danger-light': !user.status }">{{(user.status ? '诚实' : '恶意') }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

<!-- 按钮 -->
  <div class="d-flex justify-content-center mt-2 mb-2" >
    <div class="card mx-auto text-center btn bg-primary-heavy"  style="width: 30%; aspect-ratio: 14/4;" :class="{ 'disabled': isReturnButtonDisabled }"  @click="return_trace_result">
      <div class="card-body d-flex align-items-center justify-content-center" >
        <h5 class="m-0 text-white">返回结果</h5>
      </div>
    </div>
  </div>

</template>

<script setup>
import {ref, computed,onMounted,onUnmounted} from 'vue';
import {AggserverInitialEventBus, ClientInitialEventBus, TraceserverEventBus} from "@/views/event-bus";
import axios from "axios";
const initialTraceClients = [
  {name: 'user1', status: false},
  {name: 'user2', status: false},
  {name: 'user3', status: false},
  {name: 'user4', status: false},
  {name: 'user5', status: false},
  {name: 'user6', status: false},
  {name: 'user7', status: false},
  {name: 'user8', status: false},
  {name: 'user9', status: false},
  {name: 'user10', status: false},
  // 添加更多用户...
]

const initialTraceResult = [
  { name: '服务器', status: true },
  { name: 'user1', status: true },
  { name: 'user2', status: true },
  { name: 'user3', status: true },
  { name: 'user4', status: true },
  { name: 'user5', status: true },
  { name: 'user6', status: true },
  { name: 'user7', status: true },
  { name: 'user8', status: true },
  { name: 'user9', status: true },
  { name: 'user10', status: true },
]


const TraceClients = ref([]);
const TraceResult = ref([]);
let responseTime = null;

//设置axios
const apiBaseUrl = (window.webConfig && window.webConfig.webApiBaseUrl) || process.env.VUE_APP_BACKEND_API;
const apiTrace = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 从本地存储中获取用户设置
const loadTraceclientsFromLocalStorage = (option) => {
  if (option===1){
    const storedTraceClients = JSON.parse(localStorage.getItem('TraceClients'));
    console.log('storedTraceClients:',storedTraceClients);
    if (storedTraceClients) {
      TraceClients.value = storedTraceClients;
    } else {
     TraceClients.value = [...initialTraceClients];
    }
  }
  if(option===2){
    const storedTraceResult = JSON.parse(localStorage.getItem('TraceResult'));
    console.log('storedTraceResult:',storedTraceResult);
    if (storedTraceResult) {
      TraceResult.value = storedTraceResult;
    } else {
     TraceResult.value = [...initialTraceResult];
    }
    // localStorage.setItem('TraceResult', JSON.stringify(TraceResult.value));
  }


};
// 将用户设置保存到本地存储
const saveTraceclientsToLocalStorage = (option) => {
  if (option===1){
    // const rawTraceclients = Traceclients.value.map(traceclient => ({ ...traceclient }));
    localStorage.setItem('TraceClients', JSON.stringify(TraceClients.value));
    console.log('TraceClients:',TraceClients.value);
  }
  if(option===2){
    // const rawTraceResult = TraceResult.value.map(traceresult => ({ ...traceresult}));
    localStorage.setItem('TraceResult', JSON.stringify(TraceResult.value));
    console.log('TraceResult:',TraceResult.value);
  }
};
// 组件挂载时加载用户设置
onMounted(() => {

  loadTraceclientsFromLocalStorage(1);
  loadTraceclientsFromLocalStorage(2);
  console.log('Component is mounted');
});

// 组件卸载时保存用户设置到本地存储
onUnmounted(() => {
  saveTraceclientsToLocalStorage(1);
  saveTraceclientsToLocalStorage(2);
});

// 监听来自初始化按钮的事件，执行初始化操作
AggserverInitialEventBus.value.addEventListener('initializeClients', () => {
  // 重置 clients 为初始数据
  TraceClients.value = [...initialTraceClients];
  TraceResult.value = [...initialTraceResult];
  console.log('Trac Initial');
  // 将初始数据保存到本地存储
  saveTraceclientsToLocalStorage(1);
  saveTraceclientsToLocalStorage(2);
  loadTraceclientsFromLocalStorage(1);
  loadTraceclientsFromLocalStorage(2);
});
// 监听来自初始化按钮的事件，执行初始化操作
ClientInitialEventBus.value.addEventListener('initializePages', () => {
  // 重置 clients 为初始数据
  TraceClients.value = [...initialTraceClients];
  TraceResult.value = [...initialTraceResult];
  console.log('Trac Initial');
    // 将初始数据保存到本地存储
  saveTraceclientsToLocalStorage(1);
  saveTraceclientsToLocalStorage(2);
  loadTraceclientsFromLocalStorage(1);
  loadTraceclientsFromLocalStorage(2);
});

// 监听来自追踪请求的事件，执行更新
TraceserverEventBus.value.addEventListener('trace_request', (event) => {
  loadTraceclientsFromLocalStorage(1);
  const id = event.detail;
  // const id = parseInt(event.detail);
  if (id >= 0 && id < TraceClients.value.length) {
      // 访问 status 属性
      console.log('TraceClients.value[id].status:', TraceClients.value[id].status);
      TraceClients.value[id].status = true;
    } else {
      console.error('无法读取 status 属性：TraceClients 中的元素不存在或未定义');
    }
  // 将初始数据保存到本地存储
  // localStorage.setItem('TraceClients', JSON.stringify(TraceClients.value));
  saveTraceclientsToLocalStorage(1)
  console.log('Traceclients.value[id].status:', TraceClients.value[id].status);
});


const trueCount = computed(() => TraceClients.value.filter(user => user.status).length);
const buttonClass = computed(() => trueCount.value <= TraceClients.value.length / 2 ? 'btn-secondary disabled': 'bg-primary');

const hasEmptyStatus = computed(() => TraceResult.value.some(user => user.status === ''));
const isReturnButtonDisabled = computed(() => hasEmptyStatus.value);


//限制按钮在未响应前点击
const isClick = ref(false);
// 点击计时

// 点击按钮时发送 POST 请求
const start_trace = async () => {
  if (isClick.value) {
    alert('请求正在处理中...');
    return;
  }
  isClick.value = true;
  const startTime = performance.now();  // 记录开始时间
  try {
    // const response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/TraceServer`, {task:"start_trace"});
    const response = await apiTrace.post(`/TraceServer`, {task:"start_trace"});


    if (response.status === 200) {
      // 触发更新事件并传递更新的 idx 数据
      const unhonest_participants = response.data.unhonest_participants
      // TraceserverEventBus.value.dispatchEvent(new CustomEvent('trace_request', { detail: unhonest_participants }));
      unhonest_participants.forEach(index => {
        if (index >= -1 && index < TraceResult.value.length) {
          TraceResult.value[index+1].status = false;
        }
      });
      saveTraceclientsToLocalStorage(2);
      loadTraceclientsFromLocalStorage(2);
      console.log('unhonest_participants:', unhonest_participants);
      console.log('按钮的响应:', response.data);
      const endTime = performance.now();  // 记录结束时间
      responseTime = (endTime - startTime)/1000;  // 计算响应时间
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isClick.value = false;
  }
};

const return_trace_result = async () => {
  if (isClick.value) {
    alert('请求正在处理中...');
    return;
  }
  isClick.value = true;
  const storedUsers = JSON.parse(localStorage.getItem('Clients_users'));
  // let result1 = JSON.parse(localStorage.getItem('TraceResult'));
  console.log('storedUsers:',storedUsers);
  // console.log('TraceResult:',TraceResult.value);
  // console.log('result1:',result1)
  // try {
  //   const response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/TraceServer`, {task:"return_trace_result"});
  //   if (response.status === 200) {

      let return_context = []
      TraceResult.value.forEach((item, index) => {
        if (index === 0 && !item.status) {
          return_context.push('服务器');
        } else if (!item.status) {
          return_context.push(`用户${index}`);
        }
      });
      console.log('return_context:',return_context);

      console.log('TraceResult:',TraceResult.value);
      TraceClients.value.forEach((client, index) => {
        if (client.status) {
          // console.log('storedUsers ',index,'result2:',storedUsers[index]);
          storedUsers[index].result2 = return_context.join(",")
              // return_context.join(",")
        }
      });
      console.log('storedUsers:',storedUsers);
      localStorage.setItem('Clients_users', JSON.stringify(storedUsers));

    // }
  // } catch (error) {
  //   console.error('请求失败:', error);
  // } finally {
  //   isClick.value = false;
  // }
  isClick.value = false;
};

</script>

<style scoped>
.bg-primary-light {
  background-color: #5e72e4 !important; /* 淡蓝色 */
}

.bg-secondary-light {
  background-color: #aba8a8 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}
.bg-primary-heavy {
  background-color: #152ca8 !important; /* 淡蓝色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}

</style>
